/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 优化的列表视图组件 - 提升列表性能
 */

import 'package:flutter/material.dart';
import '../../viewmodels/base_network_view_model.dart';
import '../../models/page_state.dart';

/// 优化的列表视图组件
/// 实现懒加载、预加载、下拉刷新、上拉加载更多等功能
class OptimizedListView<T> extends StatefulWidget {
  /// 数据列表
  final List<T> items;

  /// 列表项构建器
  final Widget Function(BuildContext context, T item, int index) itemBuilder;

  /// 视图模型（用于状态管理）
  final BaseNetworkViewModel? viewModel;

  /// 下拉刷新回调
  final Future<void> Function()? onRefresh;

  /// 加载更多回调
  final Future<void> Function()? onLoadMore;

  /// 预加载阈值（0.0-1.0，表示滚动到列表的百分比位置时触发预加载）
  final double preloadThreshold;

  /// 是否启用下拉刷新
  final bool enableRefresh;

  /// 是否启用上拉加载更多
  final bool enableLoadMore;

  /// 列表项分隔器
  final Widget? separator;

  /// 列表项高度（用于性能优化，如果所有项高度相同）
  final double? itemExtent;

  /// 空状态组件
  final Widget? emptyWidget;

  /// 加载状态组件
  final Widget? loadingWidget;

  /// 错误状态组件
  final Widget? errorWidget;

  /// 列表内边距
  final EdgeInsetsGeometry? padding;

  /// 滚动控制器
  final ScrollController? controller;

  /// 滚动方向
  final Axis scrollDirection;

  /// 是否反向滚动
  final bool reverse;

  /// 物理滚动行为
  final ScrollPhysics? physics;

  /// 是否收缩包装
  final bool shrinkWrap;

  /// 缓存范围（屏幕外缓存的项目数量）
  final int cacheExtent;

  const OptimizedListView({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.viewModel,
    this.onRefresh,
    this.onLoadMore,
    this.preloadThreshold = 0.8,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.separator,
    this.itemExtent,
    this.emptyWidget,
    this.loadingWidget,
    this.errorWidget,
    this.padding,
    this.controller,
    this.scrollDirection = Axis.vertical,
    this.reverse = false,
    this.physics,
    this.shrinkWrap = false,
    this.cacheExtent = 250,
  });

  @override
  State<OptimizedListView<T>> createState() => _OptimizedListViewState<T>();
}

class _OptimizedListViewState<T> extends State<OptimizedListView<T>> {
  late ScrollController _scrollController;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _scrollController = widget.controller ?? ScrollController();
    _setupScrollListener();
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _scrollController.dispose();
    }
    super.dispose();
  }

  /// 设置滚动监听器
  void _setupScrollListener() {
    _scrollController.addListener(() {
      // 预加载逻辑
      if (widget.enableLoadMore &&
          widget.onLoadMore != null &&
          !_isLoadingMore &&
          widget.viewModel?.state != PageState.loading) {
        final maxScroll = _scrollController.position.maxScrollExtent;
        final currentScroll = _scrollController.position.pixels;
        final threshold = maxScroll * widget.preloadThreshold;

        if (currentScroll >= threshold) {
          _triggerLoadMore();
        }
      }
    });
  }

  /// 触发加载更多
  Future<void> _triggerLoadMore() async {
    if (_isLoadingMore) return;

    setState(() {
      _isLoadingMore = true;
    });

    try {
      await widget.onLoadMore?.call();
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果有视图模型，根据状态显示不同内容
    if (widget.viewModel != null) {
      return _buildWithViewModel();
    } else {
      return _buildListView();
    }
  }

  /// 根据视图模型状态构建内容
  Widget _buildWithViewModel() {
    final viewModel = widget.viewModel!;

    switch (viewModel.state) {
      case PageState.loading:
        if (widget.items.isEmpty) {
          return widget.loadingWidget ?? _buildDefaultLoadingWidget();
        }
        break;
      case PageState.empty:
        return widget.emptyWidget ?? _buildDefaultEmptyWidget();
      case PageState.error:
        return widget.errorWidget ??
            _buildDefaultErrorWidget(viewModel.errorMessage);
      default:
        break;
    }

    return _buildListView();
  }

  /// 构建列表视图
  Widget _buildListView() {
    Widget listView = ListView.builder(
      controller: _scrollController,
      padding: widget.padding,
      scrollDirection: widget.scrollDirection,
      reverse: widget.reverse,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap,
      cacheExtent: widget.cacheExtent.toDouble(),
      itemExtent: widget.itemExtent,
      itemCount: _getItemCount(),
      itemBuilder: (context, index) => _buildItem(context, index),
    );

    // 如果启用下拉刷新，包装 RefreshIndicator
    if (widget.enableRefresh && widget.onRefresh != null) {
      listView = RefreshIndicator(
        onRefresh: widget.onRefresh!,
        child: listView,
      );
    }

    return listView;
  }

  /// 获取列表项数量
  int _getItemCount() {
    int count = widget.items.length;

    // 如果启用加载更多且有更多数据，添加加载指示器
    if (widget.enableLoadMore &&
        (widget.viewModel?.state == PageState.loading || _isLoadingMore)) {
      count += 1;
    }

    // 如果没有更多数据，添加结束指示器
    if (widget.enableLoadMore &&
        widget.viewModel?.state == PageState.noMore &&
        widget.items.isNotEmpty) {
      count += 1;
    }

    return count;
  }

  /// 构建列表项
  Widget _buildItem(BuildContext context, int index) {
    // 如果是最后一项且是加载指示器
    if (index >= widget.items.length) {
      if (widget.viewModel?.state == PageState.loading || _isLoadingMore) {
        return _buildLoadMoreIndicator();
      } else if (widget.viewModel?.state == PageState.noMore) {
        return _buildNoMoreIndicator();
      }
      return const SizedBox.shrink();
    }

    final item = widget.items[index];
    Widget itemWidget = widget.itemBuilder(context, item, index);

    // 如果有分隔器且不是最后一项
    if (widget.separator != null && index < widget.items.length - 1) {
      itemWidget = Column(
        children: [
          itemWidget,
          widget.separator!,
        ],
      );
    }

    return itemWidget;
  }

  /// 构建默认加载组件
  Widget _buildDefaultLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('加载中...'),
        ],
      ),
    );
  }

  /// 构建默认空状态组件
  Widget _buildDefaultEmptyWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox,
            size: 64,
            color: Colors.grey,
          ),
          SizedBox(height: 16),
          Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建默认错误组件
  Widget _buildDefaultErrorWidget(String? errorMessage) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          Text(
            errorMessage ?? '加载失败',
            style: const TextStyle(
              fontSize: 16,
              color: Colors.red,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: widget.onRefresh,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 构建加载更多指示器
  Widget _buildLoadMoreIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: const Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
          SizedBox(width: 8),
          Text(
            '加载更多...',
            style: TextStyle(color: Colors.grey),
          ),
        ],
      ),
    );
  }

  /// 构建没有更多数据指示器
  Widget _buildNoMoreIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: const Text(
        '没有更多数据了',
        style: TextStyle(color: Colors.grey),
      ),
    );
  }
}

/// 优化的网格视图组件
/// 适用于专辑封面网格等场景
class OptimizedGridView<T> extends StatefulWidget {
  /// 数据列表
  final List<T> items;

  /// 列表项构建器
  final Widget Function(BuildContext context, T item, int index) itemBuilder;

  /// 交叉轴数量
  final int crossAxisCount;

  /// 主轴间距
  final double mainAxisSpacing;

  /// 交叉轴间距
  final double crossAxisSpacing;

  /// 子项宽高比
  final double childAspectRatio;

  /// 视图模型（用于状态管理）
  final BaseNetworkViewModel? viewModel;

  /// 下拉刷新回调
  final Future<void> Function()? onRefresh;

  /// 加载更多回调
  final Future<void> Function()? onLoadMore;

  /// 预加载阈值
  final double preloadThreshold;

  /// 是否启用下拉刷新
  final bool enableRefresh;

  /// 是否启用上拉加载更多
  final bool enableLoadMore;

  /// 列表内边距
  final EdgeInsetsGeometry? padding;

  /// 滚动控制器
  final ScrollController? controller;

  /// 物理滚动行为
  final ScrollPhysics? physics;

  /// 是否收缩包装
  final bool shrinkWrap;

  const OptimizedGridView({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.crossAxisCount = 2,
    this.mainAxisSpacing = 8.0,
    this.crossAxisSpacing = 8.0,
    this.childAspectRatio = 1.0,
    this.viewModel,
    this.onRefresh,
    this.onLoadMore,
    this.preloadThreshold = 0.8,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.padding,
    this.controller,
    this.physics,
    this.shrinkWrap = false,
  });

  @override
  State<OptimizedGridView<T>> createState() => _OptimizedGridViewState<T>();
}

class _OptimizedGridViewState<T> extends State<OptimizedGridView<T>> {
  late ScrollController _scrollController;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _scrollController = widget.controller ?? ScrollController();
    _setupScrollListener();
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _scrollController.dispose();
    }
    super.dispose();
  }

  /// 设置滚动监听器
  void _setupScrollListener() {
    _scrollController.addListener(() {
      // 预加载逻辑
      if (widget.enableLoadMore &&
          widget.onLoadMore != null &&
          !_isLoadingMore &&
          widget.viewModel?.state != PageState.loading) {
        final maxScroll = _scrollController.position.maxScrollExtent;
        final currentScroll = _scrollController.position.pixels;
        final threshold = maxScroll * widget.preloadThreshold;

        if (currentScroll >= threshold) {
          _triggerLoadMore();
        }
      }
    });
  }

  /// 触发加载更多
  Future<void> _triggerLoadMore() async {
    if (_isLoadingMore) return;

    setState(() {
      _isLoadingMore = true;
    });

    try {
      await widget.onLoadMore?.call();
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget gridView = GridView.builder(
      controller: _scrollController,
      padding: widget.padding,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: widget.crossAxisCount,
        mainAxisSpacing: widget.mainAxisSpacing,
        crossAxisSpacing: widget.crossAxisSpacing,
        childAspectRatio: widget.childAspectRatio,
      ),
      itemCount: widget.items.length,
      itemBuilder: (context, index) =>
          widget.itemBuilder(context, widget.items[index], index),
    );

    // 如果启用下拉刷新，包装 RefreshIndicator
    if (widget.enableRefresh && widget.onRefresh != null) {
      gridView = RefreshIndicator(
        onRefresh: widget.onRefresh!,
        child: gridView,
      );
    }

    return gridView;
  }
}
